package handler

import (
	"6-11zk/api/request"
	"6-11zk/api/response"
	"6-11zk/dao"
	"6-11zk/model"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func ProductCreate(c *gin.Context) {
	var data request.ProductCreate
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	product := model.Product{
		Model:           gorm.Model{},
		SupplierId:      data.SupplierId,
		ProductName:     data.ProductName,
		ProductGrouping: data.ProductGrouping,
		ProductCode:     data.ProductCode,
		ProductModel:    data.ProductModel,
		Unit:            data.Unit,
		CostPrice:       data.Price,
		Price:           data.Price,
		Status:          data.Status,
		Stock:           data.Stock,
		Notes:           data.Notes,
		Image:           data.Image,
	}
	err = dao.CreateProduct(&product)
	if err != nil {
		response.ResponseSuccess(c, "添加失败")
		return
	}
	response.ResponseSuccess(c, "添加成功")
}

func ProductList(c *gin.Context) {
	var data request.List
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	list, err := dao.ProductList(data.ProductGrouping)
	if err != nil {
		response.ResponseError(c, "查询失败")
		return
	}
	var lists []*model.Product
	for _, p := range list {
		lists = append(lists, &model.Product{
			Model:           gorm.Model{},
			SupplierId:      p.SupplierId,
			ProductName:     p.ProductName,
			ProductGrouping: p.ProductGrouping,
			ProductCode:     p.ProductCode,
			ProductModel:    p.ProductModel,
			Unit:            p.Unit,
			CostPrice:       p.CostPrice,
			Price:           p.Price,
			Status:          p.Status,
			Stock:           p.Stock,
			Notes:           p.Notes,
			Image:           p.Image,
		})
	}
	response.ResponseSuccess(c, lists)
}

func ProductUpdate(c *gin.Context) {
	var data request.Update
	err := c.ShouldBind(&data)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	show, err := dao.Show(data.Id)
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	show.Status = data.Status
	err = dao.UpdateStatus()
	if err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	response.ResponseSuccess(c, "修改成功")

}
